import { Course, Document, GetCourseDocument, GetDocumentDocument } from '@/generated/graphql'
import { Client } from '@urql/vue'
import { has } from 'lodash-es'
import { defineStore } from 'pinia'

interface CourseSessionStore {
  // 是否存在两种环境 云上和线下 默认: false
  isMix: boolean
  // 是否是windows 环境, 主要线下情况使用 默认: false
  isWindows: boolean
  type: 'PRIVATE' | 'PUBLIC'
  // 用户当前正在操作的课程
  course?: Course
  // 用户当前正在操作的章节
  document?: Document
  documents?: Document[]
  contentIndex: number
}

const getCourseById = async (client: Client, courseId: string) => {
  const course = await client.query(GetCourseDocument, { where: { id: courseId } }).toPromise()
  return course.data.course
}

const getDocumentById = async (client: Client, documentId: string) => {
  const document = await client.query(GetDocumentDocument, { where: { id: documentId } }).toPromise()
  return document.data.document
}

// 课程操作的相关内容
export const useCourseSessionStore = defineStore({
  id: 'course-session',
  persist: {
    storage: sessionStorage
  },
  state: (): CourseSessionStore => ({
    isMix: false,
    isWindows: false,
    course: undefined,
    document: undefined,
    documents: undefined,
    contentIndex: 0,
    type: 'PRIVATE'
  }),
  actions: {
    setMix(mix: boolean) {
      this.$patch({
        isMix: mix
      })
    },
    setWindows(isWindows: boolean) {
      this.$patch({
        isWindows
      })
    },
    setCourse(course: Course) {
      // 获取课程的backends
      const extendData = course.extends
      if (extendData) {
        if (has(extendData, 'PUBLIC') && has(extendData, 'PRIVATE')) {
          this.setMix(true) //如果课程中存在两个配置就是混合的情况
        } else {
          this.setMix(false) //其余情况都不属于混合云情况
        }
      }

      this.$patch({
        course
      })
    },
    setDocuments(documents: Document[]) {
      this.$patch({
        documents
      })
    },
    setDocument(document: Document) {
      // 获取章节的backends
      const extendData = document.extends

      //章节的配置会覆盖课程的配置
      if (extendData) {
        if (has(extendData, 'PUBLIC') && has(extendData, 'PRIVATE')) {
          this.setMix(true) //如果课程中存在两个配置就是混合的情况
        }
      }

      this.$patch({
        document
      })
    },
    async getCourseByCourseId(client: Client, courseId: string, cache: boolean = true) {
      if (cache) {
        if (this.course) {
          return this.course
        }
      }
      return await getCourseById(client, courseId)
    },
    async getDocumentByDocumentId(client: Client, documentId: string, cache: boolean = true) {
      if (cache) {
        if (this.document) {
          return this.document
        }
      }
      return await getDocumentById(client, documentId)
    },
    setType(t: 'PUBLIC' | 'PRIVATE') {
      this.$patch({
        type: t
      })
    }
  }
})
